package com.zby.simulationHibernate.util.factory;

import com.zby.simulationHibernate.util.exception.GenericException;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created By zby on 21:23 2019/1/23
 * 数据库的连接
 */
public class Connect {

    /**
     * 连接池的初始值
     */
    private static int initPoolSize = 20;

    /**
     * 创建property的配置文件
     */
    protected static Properties properties;

    /**
     * 连接池的最小值
     */
    protected static int minPoolSize;


    /**
     * 连接池的最大值
     */
    protected static int maxPoolSize;

    //【2】静态代码块
    static {
        //加载配置文件
        properties = new Properties();
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(is);
            minPoolSize = Integer.valueOf(properties.getProperty("jdbc.minConnPool"));
            if (minPoolSize <= initPoolSize)
                minPoolSize = initPoolSize;
            maxPoolSize = Integer.valueOf(properties.getProperty("jdbc.maxConnPool"));
            if (minPoolSize > maxPoolSize)
                throw new GenericException("连接池的最小连接数不能大于最大连接数");
        } catch (IOException e) {
            System.out.println("未找到配置文件");
            e.printStackTrace();
        }
    }

    /**
     * Created By zby on 16:50 2019/1/23
     * 获取数据连接
     */
    protected java.sql.Connection createConnect() {
        String driverName = properties.getProperty("jdbc.driver");
        if (StringUtils.isEmpty(driverName)) {
            driverName = "com.mysql.jdbc.Driver";
        }
        String userName = properties.getProperty("jdbc.username");
        String password = properties.getProperty("jdbc.password");
        String dbUrl = properties.getProperty("jdbc.url");

        try {
            Class.forName(driverName);
            return DriverManager.getConnection(dbUrl, userName, password);
        } catch (ClassNotFoundException e) {
            System.out.println("找不到驱动类");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("加载异常");
            e.printStackTrace();
        }
        return null;
    }
}
